<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * View file: form
 *
 * @author luubk
 * @since 12-06-2012 - 02:19:11
 */
?>
<div id="form_result"></div>
<article class="module width_full">
    <form method="POST" id="form" 
          action="<?php echo $id ? site_url("album/form/$id") : site_url("album/form") ?>">
        <header><h3><?php echo $title ?></h3></header>
        <div class="module_content">            
            <input type="hidden" name="album_vote_total" id="album_vote_total" value="<?php echo (isset($item['album_vote_total']) ? $item['album_vote_total'] : 0); ?>" />
            <input type="hidden" name="album_vote_star" id="album_vote_star" value="<?php echo (isset($item['album_vote_star']) ? $item['album_vote_star'] : 0); ?>" />
            <input type="hidden" name="album_eid" value="<?php echo (isset($item['album_eid']) ? $item['album_eid'] : ""); ?>" />

            <fieldset style="width:48%; float:left; margin-right: 3%;">
                <label>Tên album</label>
                <input type="text" style="width:92%;" id="News_news_title"
                       value="<?php echo isset($item['album_name']) ? $item['album_name'] : '' ?>"
                       onkeyup="char_limit(this, 70, '#max_title'); url_title(this, '#title_url')"
                       name="album_name" required="required">
                (Tối đa <span id="max_title">70</span> ký tự)
                <div class="clear"></div>
                <br/>
                <input type="text" style="width:92%;" id="title_url"
                       value="<?php echo isset($item['album_name_url']) ? $item['album_name_url'] : '' ?>"
                       name="album_name_url" required="required" placeholder="URL cho ứng dụng">
            </fieldset>

            <fieldset style="width:48%;float:right;">
                <label>Chọn danh mục cho album</label>               
                <div class="clear"></div>
                <?php if (isset($cate_tree)): ?>                    
                    <div style="height: 370px; overflow: auto;">    
                        <?php echo $cate_tree ?>               
                    </div>                    
                <?php endif; ?>
            </fieldset>

            <fieldset style="width:24%; float:left; margin-right: 3%;">
                <label>Hình đại diện</label>
                <div class="clear"></div>
                <div style="padding: 0 10px">                    
                    <span>
                        <a href="#" id="thumb_link">
                            <?php
                            $thumb = ($item['album_thumb'] != '') ? site_url('album/gate/' . urlencode(urlencode(urlencode($item['album_thumb'])))) : base_url() . 'assets/css/_common/images/image.png';
                            ?>
                            <img src="<?php echo $thumb ?>" 
                                 style="max-height:128px;max-width:128px"/>
                        </a>
                        <input type="hidden" value="<?php echo $item['album_thumb'] ?>" name="album_thumb" id="thumb_input"/>
                    </span>                                            
                </div>
            </fieldset>

            <fieldset style="width:21%; float:left; margin-right: 3%;">
                <label>Giá</label>
                <input type="text" style="width:80%;" value="<?php echo isset($item['album_price']) ? $item['album_price'] : '' ?>"
                       name="album_price" required="required">
            </fieldset>

            <fieldset style="width:48%; float:left; margin-right: 3%;">
                <label>Thứ tự</label>
                <input type="text" style="width:92%;" value="<?php echo isset($item['album_rank']) ? $item['album_rank'] : 0 ?>"
                       name="album_rank" required="required">
                =0 &LongRightArrow; <span style="font-size: 1.5em;color: goldenrod">&star;</span>; 
                >0 &LongRightArrow; <span style="font-size: 1.5em;color: goldenrod">&starf;</span>; 
                thứ tự lớn xếp trên
            </fieldset>

            <fieldset style="width:48%; float:right;">
                <label>Tóm tắt</label>
                <textarea rows="4" style="width:92%;" 
                          name="album_sumary"><?php echo isset($item['album_sumary']) ? $item['album_sumary'] : '' ?></textarea>
                Hiển thị trên danh sách ứng dụng
            </fieldset>            

            <fieldset style="width:48%; float:left;">
                <label>SEO</label>
                <textarea rows="4" style="width:92%;" 
                          name="album_seo"><?php echo isset($item['album_seo']) ? $item['album_seo'] : '' ?></textarea>
                Nội dung hiển thị cho bộ máy tìm kiếm
            </fieldset> 

            <fieldset style="width:100%; float:left;">
                <label>Mô tả</label>
                <textarea rows="10" style="width:92%;" 
                          name="album_desc"><?php echo isset($item['album_desc']) ? $item['album_desc'] : '' ?></textarea>
                Hiển thị trên chi tiết ứng dụng
            </fieldset>          
            <div class="clear"></div>            

            <fieldset>
                <label>Ảnh trong album</label>
                <div class="clear"></div>
                <div style="padding: 0 10px">
                    <table class="tablesorter" cellspacing="0" style="margin: 0">         
                        <thead>
                            <tr id="">                                
                                <th width="20%">Ảnh</th>
                                <th width="10%">Cỡ</th>
                                <th width="40%">Mô tả</th>
                                <th width="10%">HĐ</th>
                                <th width="10%">Sắp xếp</th>
                                <th width="10%">Thumbnail</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (isset($photos) && !empty($photos)): ?>
                                <?php foreach ($photos as $file): ?>
                                    <?php $photo_id = 'photo_' . $file['photo_id'] ?>
                                    <tr id="<?php echo $photo_id ?>">                                        
                                        <td>                                            
                                            <?php if (!file_exists(ALBUM_DIR . $file['photo_file'])): ?>
                                                <p style="color:red">                                                
                                                    * File không tồn tại trên hệ thống, bạn vui lòng cập nhật lại
                                                </p>                         
                                            <?php else: ?>
                                                <img src="<?php echo site_url('album/gate/' . urlencode(urlencode(urlencode($file['photo_file'])))) ?>"
                                                     alt="<?php echo basename($file['photo_file']) ?>" 
                                                     style="max-height: 128px"/>
                                                 <?php endif; ?>
                                            <input type="hidden" value="<?php echo $file['photo_id'] ?>" name="photo[<?php echo $photo_id ?>][photo_id]">
                                            <input type="hidden" value="<?php echo $file['photo_file'] ?>" name="photo[<?php echo $photo_id ?>][photo_file]">
                                            <input type="hidden" value="<?php echo $file['photo_rank'] ?>"
                                                   id="photo_rank_<?php echo $photo_id ?>"
                                                   name="photo[<?php echo $photo_id ?>][photo_rank]">
                                        </td>                                        
                                        <td align="center">
                                            <?php echo byte_format($file['photo_size']) ?>
                                            <input type="hidden" value="<?php echo $file['photo_size'] ?>" name="photo[<?php echo $photo_id ?>][photo_size]">
                                        </td>                                        
                                        <td>
                                            <textarea rows="5" style="width: 80%" name="photo[<?php echo $photo_id ?>][photo_desc]"><?php echo $file['photo_desc'] ?></textarea>
                                        </td>                                        
                                        <td>
                                            &nbsp;&nbsp;
                                            <a href="#" onclick="return del_photo('<?php echo $file['photo_id'] ?>');">Xóa</a>
                                        </td>
                                        <td>
                                            <a href="#" title="lên trên" onclick="return photo_up($(this))">
                                                lên
                                            </a> 
                                            | 
                                            <a href="#" title="xuống dưới"  onclick="return photo_down($(this))">
                                                xuống
                                            </a>
                                        </td>                                        
                                        <td style="text-align: center">                                            
                                            <input type="radio" name="make_thumb" onclick="make_thumbnail($(this))"
                                                   data="<?php echo site_url('album/gate/' . urlencode(urlencode(urlencode($file['photo_file'])))) ?>"
                                                   <?php echo $item['album_thumb'] == $file['photo_file'] ? 'checked=""' : '' ?> 
                                                   value="<?php echo $file['photo_file'] ?>" />
                                        </td>                                        
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            <tr id="photo_link_wrap" >
                                <td colspan="5">
                                    <a href="#" id="photo_link">Upload ảnh mới</a> | 
                                    <a href="#" onclick="return crawler_file();">Nhập URL ảnh</a> | 
                                    <a href="#" id="photo_crawler">Crawl ảnh từ bài viết</a> | 
                                </td>
                            </tr>
                        </tbody>
                    </table>      
                </div>                
            </fieldset>
            <div class="clear"></div>            
        </div>
        <footer>
            <div class="submit_link">
                <span class="loading">&nbsp;</span>
                <select name="album_status">
                    <option value="1" <?php echo (isset($item['album_status']) && $item['album_status'] == 1) ? 'selected="selected"' : '' ?>>Kích hoạt</option>
                    <option value="0" <?php echo (isset($item['album_status']) && $item['album_status'] == 0) ? 'selected="selected"' : '' ?>>Vô hiệu hóa</option>
                </select>
                <input type="submit" value="Lưu lại" class="alt_btn">
                <input type="reset" value="Nhập lại" onclick="reset_crawler()">                
            </div>
        </footer>
    </form>
</article><!-- end of post new article -->
<div id="thumb_dialog" title="Upload ảnh đại diện cho ứng dụng từ máy của bạn">
    <div id="thumb_result" style="text-align: center"></div>
    <form method="POST" enctype="multipart/form-data"
          action="<?php echo site_url('album/upload_thumb') ?>" id="thumb_frm" >        
        <input type="file" name="userfile" size="20" id="thumb_file"/>        
        <div class="progressbar"></div>
    </form>    
</div>
<div id="photo_dialog" title="Upload ảnh từ máy của bạn">
    <div id="photo_result" style="text-align: center"></div>
    <form method="POST" enctype="multipart/form-data"
          action="<?php echo site_url('album/upload_photo') ?>" id="photo_frm" >
        <p>
            <label for="photo_desc">Mô tả</label><br/>
            <textarea name="photo_desc" id="photo_desc" style="width: 97%" rows="4"></textarea>
        </p>
        <p>            
            <input type="file" name="userfile" size="20" id="photo_file"/>        
        </p>
        <div class="progressbar"></div>
    </form>    
</div>
<div id="crawler_dialog" title="Chọn URL để Crawler ảnh">
    <p>
        <label for="photo_desc">URL</label><br/>
        <textarea name="photo_desc" id="crawler_url" style="width: 97%" rows="2"></textarea>
        <br/>
    </p>
    <div class="progressbar"></div>
    <div id="crawler_result" style="text-align: center" >
    </div>
</div>
<script>
    function del_photo(id)
    {
        photo_id = '#photo_' + id;
        if(confirm('Bạn có chắc là muốn xóa ảnh này không?'))
        {
            $(photo_id).remove();
            del_file_input = '<input type="hidden" name="photo_del[]" value="' + id + '"/>';
            $('#photo_link_wrap').after(del_file_input);
            
        }
        auto_rank();
        return false;
    }
    
    $(document).ready(function() {                     
        $("#photo_crawler").click(function(){                  
            $( ".progressbar" ).progressbar( "option", "value", 0 );        
            $("#crawler_dialog").dialog("open");
            return false;
        });
        
        $("#crawler_dialog").dialog({
            width: 400,
            autoOpen: false,            
            buttons: {
                "Crawl": function() {
                    urlCrawler = $("#crawler_url").val();
                    if(urlCrawler == '')
                    {
                        alert('Bạn vui lòng nhập url');
                        $("#crawler_url").focus();
                        return false;
                    }
                    url = "<?php echo site_url('album/crawler') ?>";
                    $.post(url, {url:urlCrawler}, function(data){
                        $("#photo_link_wrap").before(data);
                        $('.crawler').each(function(){
                            remove_small_image($(this), $(this).attr('data'));
                        });
                    })
                    $(this).dialog("close");                    
                },
                "Đóng": function() {
                    $( ".progressbar" ).progressbar( "option", "value", 0 );
                    $(this).dialog("close");
                    $("#photo_result").html("");
                }
            }       
        });
    
    });
    
    function crawler_file()
    {        
        url = '';
        while (url === '')
        {                            
            url = window.prompt("Nhập URL của ảnh","");
        }
        id = jQuery.now();
        
        IsValidImageUrl(url, id); 
        return false;
    }
    
    function IsValidImageUrl(url, id) {
        $("<img>", {
            src: url,
            error: function() {
                alert('URL của ảnh không chính xác hoặc không tồn tại');
            },
            load: function() {
                insert_crawler_file(id, url);                
            }
        });
    }
    
    function insert_crawler_file(id, url)
    {
        data = '<tr class="crawler" id="' + id + '">';
        data += '<td><img style="max-height: 128px" src="' + url + '" />';
        data += '<input type="hidden" value="' + url + '" class="crawler_file"  name="crawler['+ id + '][photo_file]" />';
        data += '<input type="hidden" value="0" class="crawler_file" id="photo_rank_'+ id + '" name="crawler['+ id + '][photo_rank]" />';
        data += '<div class="crawler_result"></div></td>';
        data += '<td>N/A</td>';
        data += '<td><textarea rows="5" style="width: 80%" class="crawler_desc"  name="crawler['+ id + '][photo_desc]"></textarea></td>';
        data += '<td><a onclick="$(this).parent().parent().remove(); return false;" href="#">xóa</a></td>';
        data += '<td><a href="#" title="lên trên" onclick="return photo_up($(this))">lên</a>';
        data += '| <a href="#" title="xuống dưới" onclick="return photo_down($(this))">xuống</a></td>';
        data += '<td>';
        data += '<input type="radio" name="make_thumb" class="make_thumb" value="' + id + '"/>';
        data += '</td>';
        data += '</tr>';
        $("#photo_link_wrap").before(data);
        auto_rank();
    }
    
    
    function crawler_chose(el, id)
    {
        url = el.attr('href');        
        insert_crawler_file(id, url)
        el.parent().remove();
        return false;
    }
    
    function call_crawler(album_id)
    {   
        update_url = '<?php echo site_url("album/form") ?>/' + album_id;
        $('#form').attr('action', update_url);
        $('.crawler').each(function(){
            crawling($(this), album_id);
        });
        
        $('.crawler').ajaxStart(function() {
            validNavigation = false;
            wireUpEvents('Một số thao tác vẫn đang thực hiện, bạn vui lòng chờ trong giây lát!');
        }).ajaxStop(function() {
            validNavigation = true;
            data = '<h4 class="alert_success">Crawl ảnh thành công!<h4>';
            $("#form_result").html(data);
            window.scrollTo(0,0) ;	
            return;
        })
        
        data = '<h4 class="alert_success">Thêm album ảnh thành công!<h4>';
        $("#form_result").html(data);
        window.scrollTo(0,0) ;	
    }
    
    function crawling(el, album_id)
    {
        id = el.attr('id');
        file = el.children().children('.crawler_file').attr('value');
        desc = el.children().children('.crawler_desc').attr('value');
        is_thumb = 0;
        if(el.children().children('.make_thumb').is(':checked'))
            is_thumb = 1;
        
        result = el.children().children('.crawler_result');
        result.html('crawling <img src="<?php echo $assets ?>/images/loading.gif" />');
        url = '<?php echo site_url("album/save_crawler_file"); ?>';
        $.post(url, {album_id: album_id, file:file, desc:desc, id:id, is_thumb:is_thumb}, function(json){
            $('#' + json.message).children().children('.crawler_result').html(json.data);
            el.attr('class', '');
        }, 'json');
    }            
    
    function remove_small_image(el, url)
    {
        // Tạo đối tượng ảnh        
        var theImage = new Image();
        // Trường hợp load được ảnh
        theImage.onload = function() {
            // Nếu ảnh có chiều rộng hoặc chiều cao nhỏ hơn 200
            if(theImage.width < 200 || theImage.height < 200)
            {   
                console.log(url + " " +  theImage.width + "x"+ theImage.height)
                el.remove();       
            }        
        }
        // Xóa ảnh nếu không load được
        theImage.onerror = function(){
            el.remove();
        }
        theImage.src = url;                                
    }
    
    $("body").on("mouseenter mouseleave", "img", function(){
        $(this).tooltip({ 
            delay: 0, 
            opacity: 0,
            showURL: false, 
            bodyHandler: function() { 
                return $("<img/>").attr("src", this.src); 
            } 
        });
    });

    
    function auto_rank()
    {        
        $('tr').each(function(){            
            id = $(this).attr('id');
            $('#photo_rank_' + id).val($(this).index())
        });
    }

    
    function reset_crawler()
    {
        $('.crawler').remove();
    }        
    
    function make_thumbnail(el)
    {
        $('#thumb_input').val(el.attr('value'));
        $('#thumb_link').children('img').attr('src', el.attr('data'));
    }
    
    auto_rank();
    jQuery.fn.outerHTML = function() {
        return jQuery('<div />').append(this.eq(0).clone()).html();
    };
    
    $(document).ajaxStop(function(){
        auto_rank();
    });
</script>